package com.apobates.forum.thrones.event;

import com.github.davidmarquis.redisq.Message;
import com.github.davidmarquis.redisq.consumer.MessageListener;
import com.github.davidmarquis.redisq.consumer.retry.RetryableMessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.PostsMoodRecords;
import com.apobates.forum.core.entity.proxy.TopicReplica;
import com.apobates.forum.core.impl.event.PostsMoodEvent;
import com.apobates.forum.core.service.PostsService;
import com.apobates.forum.letterbox.entity.ForumLetter;
import com.apobates.forum.letterbox.entity.ForumLetterReceiver;
import com.apobates.forum.letterbox.service.ForumLetterService;
import com.apobates.forum.utils.DateTimeUtils;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;

/**
 * 回复喜好动作通知
 *
 * @author xiaofanku
 * @since 20191116
 */
@Component("moodActionNotice")
public class PostsMoodNoticeListener implements MessageListener<PostsMoodEvent> {
    @Autowired
    private PostsService postsService;
    @Autowired
    private ForumLetterService forumLetterService;
    private final static Logger logger = LoggerFactory.getLogger(PostsMoodNoticeListener.class);
    
    @Override
    public void onMessage(Message<PostsMoodEvent> event) throws RetryableMessageException {
        PostsMoodRecords pmr = event.getPayload().getRecords();
        if (!pmr.isLiked()) {
            return; //讨厌的都不通知了
        }
        Optional<Posts> posts = postsService.get(pmr.getPostsId());
        if (!posts.isPresent()) {
            return; //回复不存在
        }
        logger.info("[Posts][MoodEvent][1]回复喜好通知处理开始");
        Posts p = posts.get();
        String floorLink = String.format("/topic/%s.xhtml#posts-%d", TopicReplica.generateConnectString(p.getTopicId(), p.getBoardId(), p.getVolumesId()), p.getId());
        String content = String.format("<p>%s在%s为您的回复点赞, <a class=\"embed-link\" href=\"%s\">查看回复</a></p>", pmr.getMemberNickname(), DateTimeUtils.getRFC3339(pmr.getEntryDateTime()), floorLink);
        forumLetterService.create(
                ForumLetter.noticeLetter("您的回复收到一条点赞记录", content), 
                List.of(new ForumLetterReceiver(p.getMemberId(), p.getMemberNickname())));
        logger.info("[Posts][MoodEvent][1]回复喜好通知处理结束");
    }
}